const express = require('express')
const cors = require('cors')
const axios = require('axios')
const path = require('path')

const app = express()
const PORT = 3001

// 中间件
app.use(cors())
app.use(express.json())

// 静态文件服务（如果需要）
app.use(express.static(path.join(__dirname, 'dist')))

// GMGN API 代理路由
app.get('/api/token-holders/:address', async (req, res) => {
  const { address } = req.params
  const { limit = 100, orderby = 'amount_percentage', direction = 'desc' } = req.query
  
  console.log(`\n=== 收到API请求 ===`)
  console.log(`时间: ${new Date().toLocaleString()}`)
  console.log(`地址: ${address}`)
  console.log(`参数: limit=${limit}, orderby=${orderby}, direction=${direction}`)
  
  try {
    const requestUrl = `https://gmgn.ai/vas/api/v1/token_holders/sol/${address}`
    const requestParams = {
      app_lang: 'zh-CN',
      os: 'web',
      limit: parseInt(limit),
      cost: 20,
      orderby,
      direction
    }
    
    console.log(`\n--- 开始请求GMGN API ---`)
    console.log(`请求URL: ${requestUrl}`)
    console.log(`请求参数:`, JSON.stringify(requestParams, null, 2))
    console.log(`超时设置: 30000ms`)
    
    const startTime = Date.now()
    
    const response = await axios.get(requestUrl, {
      params: requestParams,
      timeout: 30000, // 30秒超时
      headers: {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        'Accept': 'application/json, text/plain, */*',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'Cache-Control': 'no-cache'
      }
    })
    
    const endTime = Date.now()
    const duration = endTime - startTime
    
    console.log(`\n--- GMGN API响应成功 ---`)
    console.log(`响应时间: ${duration}ms`)
    console.log(`状态码: ${response.status}`)
    console.log(`响应数据大小: ${JSON.stringify(response.data).length} 字符`)
    
    if (response.data && response.data.data && response.data.data.list) {
      console.log(`持有人数量: ${response.data.data.list.length}`)
    }
    
    // 转换数据格式
    const transformedData = {
      success: response.data.code === 0,
      data: {
        items: response.data.data.list.map(item => ({
          owner: item.address,
          amount: item.amount_cur,
          percentage: item.amount_percentage * 100, // 转换为百分比
          profit: item.profit || 0,
          profit_rate: item.avg_cost ? ((item.amount_cur * item.avg_cost - item.cost_cur) / item.cost_cur * 100) : 0,
          trade_type: item.buy_amount_cur > item.sell_amount_cur ? 'buy' : 'sell',
          is_internal: item.is_suspicious || false,
          source: item.wallet_tag_v2 || '未知',
          transfer_time: item.start_holding_at
        })),
        total: response.data.data.list.length
      }
    }
    
    console.log(`\n--- 数据转换完成 ---`)
    console.log(`转换后数据项数: ${transformedData.data.items.length}`)
    console.log(`=== API请求完成 ===\n`)
    
    res.json(transformedData)
    
  } catch (error) {
    const endTime = Date.now()
    const duration = endTime - startTime
    
    console.log(`\n--- GMGN API请求失败 ---`)
    console.log(`错误类型: ${error.name}`)
    console.log(`错误消息: ${error.message}`)
    console.log(`错误代码: ${error.code}`)
    console.log(`请求时长: ${duration}ms`)
    
    if (error.response) {
      console.log(`响应状态: ${error.response.status}`)
      console.log(`响应数据:`, error.response.data)
    } else if (error.request) {
      console.log(`请求对象:`, error.request)
    }
    
    console.log(`完整错误信息:`, error)
    
    // 返回模拟数据作为备用
    const mockData = {
      success: true,
      data: {
        items: [
          {
            owner: '4eFAJp73mKWefZoJTn7CiPodta5UHvcSSHJeS31xTkzv',
            amount: 331061981.222121,
            percentage: 33.11,
            profit: 14178.37,
            profit_rate: 12.5,
            trade_type: 'buy',
            is_internal: false,
            source: 'TOP1',
            transfer_time: 1757418419
          },
          {
            owner: '7J2rKHs3j5ZBaaFFSRPpbKe7vxRLVpmz3YaSjtH8pT1P',
            amount: 195366400.0,
            percentage: 19.54,
            profit: 8500.25,
            profit_rate: 8.3,
            trade_type: 'buy',
            is_internal: false,
            source: '未知',
            transfer_time: 1757418000
          },
          {
            owner: '9PioBysuEs4gVhcaUYkzKDdW9BRcWqTek1Ew7bwdpump',
            amount: 150000000.0,
            percentage: 15.0,
            profit: 6500.0,
            profit_rate: 5.2,
            trade_type: 'sell',
            is_internal: true,
            source: '未知',
            transfer_time: 1757417500
          },
          {
            owner: 'ABC123def456GHI789jkl012MNO345pqr678',
            amount: 120000000.0,
            percentage: 12.0,
            profit: 5200.0,
            profit_rate: 4.3,
            trade_type: 'buy',
            is_internal: false,
            source: '未知',
            transfer_time: 1757417000
          },
          {
            owner: 'XYZ789uvw012RST345yza678BCD901efg234',
            amount: 95000000.0,
            percentage: 9.5,
            profit: 4100.0,
            profit_rate: 3.2,
            trade_type: 'sell',
            is_internal: true,
            source: '未知',
            transfer_time: 1757416500
          }
        ],
        total: 5
      }
    }
    
    console.log(`\n--- 使用模拟数据 ---`)
    console.log(`模拟数据项数: ${mockData.data.items.length}`)
    console.log(`=== 请求处理完成 ===\n`)
    
    res.json(mockData)
  }
})

// 健康检查路由
app.get('/health', (req, res) => {
  res.json({ status: 'ok', message: 'Server is running' })
})

// 启动服务器
app.listen(PORT, () => {
  console.log(`🚀 后端服务器运行在 http://localhost:${PORT}`)
  console.log(`📡 GMGN API 代理: http://localhost:${PORT}/api/token-holders/:address`)
  console.log(`💚 健康检查: http://localhost:${PORT}/health`)
})

// 优雅关闭
process.on('SIGTERM', () => {
  console.log('收到 SIGTERM 信号，正在关闭服务器...')
  process.exit(0)
})

process.on('SIGINT', () => {
  console.log('收到 SIGINT 信号，正在关闭服务器...')
  process.exit(0)
})
